/**
 * 聊天API服务
 */
import { callTencentCloudAPI } from '../utils/tencentCloud';
import { tencentCloudConfig } from '../utils/config';
import type { ChatMessage, Reference } from '../types';

/**
 * 发送聊天消息并获取回复
 * @param message 用户输入的消息
 * @param history 历史聊天记录
 * @returns 返回AI助手的回复消息
 */
export const sendChatMessage = async (message: string, history: ChatMessage[]): Promise<ChatMessage> => {
  try {
    // 构建聊天历史
    const chatHistory = history.map(msg => ({
      role: msg.role,
      content: msg.content,
    }));
    
    // 调用腾讯云Chat API
    const response = await callTencentCloudAPI<{
      Response: string;
      References?: Reference[];
    }>('Chat', {
      BotBizId: tencentCloudConfig.botBizId,
      Query: message,
      History: chatHistory,
    });
    
    if (response.code === 0) {
      return {
        id: Date.now().toString(),
        content: response.data.Response || '抱歉，我无法回答您的问题。',
        role: 'assistant',
        timestamp: Date.now(),
        references: response.data.References || [],
      };
    }
    
    throw new Error(response.message);
  } catch (error) {
    console.error('发送消息失败:', error);
    
    // 返回错误消息
    return {
      id: Date.now().toString(),
      content: '抱歉，服务出现了问题，请稍后再试。',
      role: 'assistant',
      timestamp: Date.now(),
      references: [],
    };
  }
};

/**
 * 获取引用来源详情
 * @param referBizIds 引用源ID数组
 * @returns 引用来源详情数组
 */
export const getReferenceSources = async (referBizIds: string[]): Promise<Reference[]> => {
  if (!referBizIds.length) return [];
  
  const response = await callTencentCloudAPI<{ List: Reference[] }>('DescribeRefer', {
    BotBizId: tencentCloudConfig.botBizId,
    ReferBizIds: referBizIds,
  });
  
  return response.code === 0 ? response.data.List : [];
}; 